package lvbu.wang.lvbuoperator.ui.index;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.google.gson.Gson;
import com.qing.library.utils.ToastUtil;
import com.yzq.zxinglibrary.common.Constant;

import java.util.HashMap;
import java.util.Map;

import lvbu.wang.lvbuoperator.Quick;
import lvbu.wang.lvbuoperator.R;
import lvbu.wang.lvbuoperator.bean.JsonMessage;
import lvbu.wang.lvbuoperator.bean.MotorInfo;
import lvbu.wang.lvbuoperator.constants.ConstantsValue;
import lvbu.wang.lvbuoperator.constants.RouteConstant;
import lvbu.wang.lvbuoperator.core.App;
import lvbu.wang.lvbuoperator.core.BaseActivity;
import lvbu.wang.lvbuoperator.http.IotHttpHelp;
import lvbu.wang.lvbuoperator.manager.ThreadPool;
import lvbu.wang.lvbuoperator.ui.paramset.ui.IotParamSetActivity;
import lvbu.wang.lvbuoperator.ui.scan.IotBluetoothListActivity;

/**
 * Created by DaiQing.Zha on 2016/9/19 0019.
 */
public class IotIndexActivity extends BaseActivity implements View.OnClickListener {

    private EditText mEtImei, mEtImeiPrefix;    //imei，imei前缀
    private Button mBtnSubmit, mBtnSetting; //提交，设置
    private Button mBtnScanEWM, mBtnBleList;    //扫描二维码，蓝牙列表

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_iot_index);
    }

    @Override
    protected void init() {
        mEtImei = findView(R.id.et_imei);
        mEtImeiPrefix = findView(R.id.et_imeiPrefix);
        mBtnSubmit = findView(R.id.btn_submit);
        mBtnSetting = findView(R.id.btn_setting);
        mBtnScanEWM = findView(R.id.btn_scanEWM);
        mBtnBleList = findView(R.id.btn_bleList);
        mBtnSubmit.setOnClickListener(this);
        mBtnSetting.setOnClickListener(this);
        mBtnScanEWM.setOnClickListener(this);
        mBtnBleList.setOnClickListener(this);
        findView(R.id.btn_scan_imei).setOnClickListener(this);
        BaseActivity.setMotorType(IotIndexActivity.this, ConstantsValue.MOTOR_TYPE_IOT_OPERATION);
        getSupportActionBar().setTitle(getString(R.string.app_iot_name));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_submit:
                submit();
                break;
            case R.id.btn_setting:
                setting();
                break;
            case R.id.btn_bleList:
                startActivity(new Intent(IotIndexActivity.this, IotBluetoothListActivity.class));
                break;
            case R.id.btn_scanEWM:
                Quick.startQRCode(this, ConstantsValue.INTENT_SCAN_EWM);
//                startActivityForResult(new Intent(IotIndexActivity.this, CaptureActivity.class), ConstantsValue.INTENT_SCAN_EWM);
                break;
            case R.id.btn_scan_imei:
                Quick.startQRCode(this, 1231);
                break;
        }
    }

    /**
     * 设置
     */
    private void setting() {

        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {

                String imeiPrefix = mEtImeiPrefix.getText().toString().trim();
                Map<String, Object> queryStrings = new HashMap<String, Object>();
                queryStrings.put("managerId", getManagerId());
                queryStrings.put("imeiPrefix", imeiPrefix);
                queryStrings.put("kind", "assemblySet");
                String source = IotHttpHelp.getData(RouteConstant.SET_MANAGER_MOTOR_IMEI_PREFIX_INSERT, queryStrings, true, IotIndexActivity.this);
                if (source.equals(JsonMessage.True) == false) {
                    showToastMsg(getString(R.string.xml_iotIndex_setImeiSuccess));
                } else {
                    showToastMsg(getString(R.string.xml_iotIndex_setImeiFail));
                }
            }
        });
    }

    private static final String TAG = "IotIndexActivity";

    /**
     * 提交
     */
    private void submit() {

        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {

                String imei = mEtImei.getText().toString().trim();
                Map<String, Object> queryStrings = new HashMap<String, Object>();
                queryStrings.put("imei", imei);
                String source = IotHttpHelp.getData(RouteConstant.GET_JSON_MOTOR_MOTOR_INFO_BY_IMEI, queryStrings, true, IotIndexActivity.this);
                Log.e(TAG, "run: " + source, null);
                if (IotHttpHelp.checkSource(source)) {
                    MotorInfo motorInfo = new Gson().fromJson(source, MotorInfo.class);
                    if (motorInfo.getMotorId() > 0) {
                        App.getInstance().setMotor(motorInfo);
                        String statusCode = motorInfo.getStatusCode();
                        Bundle bundle = new Bundle();
                        bundle.putLong("motorId", motorInfo.getMotorId());
                        bundle.putBoolean("isOnline", motorInfo.getIsOnline());
                        bundle.putString("imei", motorInfo.getImei());
                        bundle.putString("bluetoothAddress", motorInfo.getBluetoothAddress());
                        bundle.putString("iccId", motorInfo.getIccid());
                        bundle.putString("typeName", motorInfo.getTypeName());
                        bundle.putString("circumference", motorInfo.getCircumference() + "");
                        bundle.putString("statusCode", statusCode);
                        App.getInstance().setMotor(motorInfo);
                        setBluetoothAddress(IotIndexActivity.this, motorInfo.getBluetoothAddress());
                        Intent intent = new Intent(IotIndexActivity.this, IotParamSetActivity.class);
                        intent.putExtra("bundle", bundle);
                        Log.e("mainHHH", "source = " + source);
                        startActivity(intent);
                    } else {
                        showToastMsg("此IMEI无对应电机！");
                    }
                } else {
                    showToastMsg(IotHttpHelp.source2Message(IotIndexActivity.this, source));
                }
            }
        });
    }


    /**
     * 开启相关权限
     */
    private void openAuthority() {
        new AlertDialog.Builder(this).setTitle(getString(R.string.comm_tip)).setMessage(getString(R.string.cameraLimit_dialogMsg)).setPositiveButton(getString(R.string.comm_sure), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.setData(Uri.fromParts("package", getPackageName(), null));
                startActivity(intent);
            }
        }).setNegativeButton(getString(R.string.comm_cancel), null)
                .show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.out.println(requestCode + "-----");
        switch (requestCode) {
            case ConstantsValue.INTENT_SCAN_EWM:   //从绑定车辆返回过来
                if (resultCode == RESULT_OK) {    //返回结果成功
                    Bundle bundle = data.getExtras();
                    final String barcode = bundle.getString(Constant.CODED_CONTENT).trim();
                    if (barcode.equals("error")) {
                        openAuthority();
                        return;
                    }
                    ThreadPool.getInstance().addTask(new Runnable() {
                        @Override
                        public void run() {
                            Map<String, Object> queryStrings = new HashMap<String, Object>();
                            queryStrings.put("barcode", barcode.trim());
                            final String source = IotHttpHelp.getData(RouteConstant.GET_MOTOR_ID_SELECT_BY_BARCODE, queryStrings, true, IotIndexActivity.this);
                            if ("0".equals(source)) {
                                showToastMsg(getString(R.string.toast_iotIndex_ewmNoWheelHub));
                                return;
                            } else {
                                long motorId = Long.parseLong(source);
                                queryStrings.put("motorId", motorId);
                                final String source_ = IotHttpHelp.getData(RouteConstant.GET_MOTOR_INFO_BY_MOTOR_ID, queryStrings, true, IotIndexActivity.this);
                                final MotorInfo motorInfo = new Gson().fromJson(source_, MotorInfo.class);
                                if (motorInfo.getMotorId() > 0) {
                                    String statusCode = motorInfo.getStatusCode();
                                    Bundle bundle = new Bundle();
                                    bundle.putLong("motorId", motorInfo.getMotorId());
                                    bundle.putBoolean("isOnline", motorInfo.getIsOnline());
                                    bundle.putString("imei", motorInfo.getImei());
                                    bundle.putString("bluetoothAddress", motorInfo.getBluetoothAddress());
                                    bundle.putString("iccId", motorInfo.getIccid());
                                    bundle.putString("typeName", motorInfo.getTypeName());
                                    bundle.putString("circumference", motorInfo.getCircumference() + "");
                                    bundle.putString("statusCode", statusCode);
                                    setBluetoothAddress(IotIndexActivity.this, motorInfo.getBluetoothAddress());
                                    App.getInstance().setMotor(motorInfo);
                                    Intent intent = new Intent(IotIndexActivity.this, IotParamSetActivity.class);
                                    intent.putExtra("bundle", bundle);
                                    startActivity(intent);
                                } else {
                                    showToastMsg(getString(R.string.toast_iotIndex_imeiNoMotor));
                                }
                            }
                        }
                    });
                }
                break;
            case 1231:
                if (resultCode == RESULT_OK) {    //返回结果成功
                    Bundle bundle = data.getExtras();
                    String s = bundle.getString(Constant.CODED_CONTENT).trim();
                    if (!s.isEmpty() && s.contains(";")) {
                        ToastUtil.showShortToast(this, "IMEI值获取成功");
                        mEtImei.setText(s.split(";")[0]);
                    } else {
                        // 不包含; 或者为空
                        ToastUtil.showShortToast(this, "二维码错误-1");
                    }
                }
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {
                Map<String, Object> queryStrings = new HashMap<String, Object>();
                queryStrings.put("managerId", getManagerId());
                queryStrings.put("kind", "assemblySet");
                final String source = IotHttpHelp.getData(RouteConstant.GET_MANAGER_MOTOR_IMEI_PREFIX_SELECT_NEW_BY_MANAGER_ID, queryStrings, true, IotIndexActivity.this);
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
//                        String imeiPrefix = source.replace("\"", "");
//                        mEtImei.setText(imeiPrefix);
//                        Editable etext = mEtImei.getText();
//                        Selection.setSelection(etext, etext.length());
                    }
                });
            }
        });
    }
}
